﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ywxt.Common;

namespace ZJCQ.Controllers.CategoryManage
{
    using NHibernate.Criterion;
    using DB_NH;
    using ZJK.Models.CategoryManage;

    [Authorize]
    public class CategoryController : Controller
    {
        //
        // GET: /Category/


        /// <summary>
        /// 显示专家管理的操作菜单
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult OPMenu()
        {
            return PartialView();
        }

        /// <summary>
        /// 首页，查询专家分类列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 根据ID，获取类型信息
        /// </summary>
        /// <param name="kwCategoryId"></param>
        /// <returns></returns>
        public JsonResult getCategorys()
        {
            List<vmCategoryForJson> _returnValue = new List<vmCategoryForJson>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _categorys = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                            .Where(c => c.IsValid == 1)
                            .OrderBy(c => c.category_level).Asc()
                            .OrderBy(c => c.category_code).Asc()
                            .List();

                        foreach (var _c in _categorys)
                        {
                            vmCategoryForJson _vmc = new vmCategoryForJson()
                            {
                                id = _c.Id,
                                name = "[" + _c.category_code + "]" + _c.category_name
                            };

                            if (_c.pre_category != null)
                            {
                                _vmc.pId = _c.pre_category.Id;
                            }
                            else
                            {
                                _vmc.pId = "0";
                            }
                            _returnValue.Add(_vmc);
                        }
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        throw ex;
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据类型ID，获取类型信息
        /// </summary>
        /// <returns></returns>
        public JsonResult getCategoryByID(string category_id)
        {
            vmCategory _returnValue = new vmCategory();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _category = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                            .Where(c => c.IsValid == 1 && c.Id == category_id)
                            .SingleOrDefault();

                        if (_category != null)
                        {
                            _returnValue.id = _category.Id;
                            _returnValue.code = _category.category_code;
                            _returnValue.name = _category.category_name;
                            if (_category.pre_category != null)
                            {
                                _returnValue.pid = _category.pre_category.Id;
                            }
                            else
                            {
                                _returnValue.pid = "";
                            }
                            _returnValue.isleaf = _category.is_leaf == 1;
                        }
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        throw ex;
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 添加一个根节点
        /// </summary>
        /// <returns></returns>
        public JsonResult newRootCategory()
        {
            string _returnValue = string.Empty;

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var root = new DB_NH.DB_Model.ZJK.ZJ_category()
                        {
                            Id = Common.NewID(),
                            is_leaf = 1,
                            category_code = "新类型代码",
                            category_level = 1,
                            category_name = "新类型名称",
                            pre_category = null
                        };
                        root.category_path = root.Id;

                        session.SaveOrUpdate(root);

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        _returnValue = "系统执行操作错误，错误代码：" + ex.Message;
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 添加指定类型ID的一个子节点
        /// </summary>
        /// <returns></returns>
        public JsonResult newSubCategory(string thisCategoryId)
        {
            string _returnValue = string.Empty;

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var preCategory = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                            .Where(c => c.IsValid == 1 && c.Id == thisCategoryId)
                            .SingleOrDefault();

                        if (preCategory != null)
                        {
                            //判断当前类型是否有子类型
                            if (preCategory.sub_categorys.Count > 0)
                            {
                                //处理有子类型的父节点：直接添加子类型节点
                                var new_rec = new DB_NH.DB_Model.ZJK.ZJ_category()
                                {
                                    Id = Common.NewID(),
                                    is_leaf = 1,
                                    category_code = "新类型代码",
                                    category_level = 1,
                                    category_name = "新类型名称",
                                    pre_category = preCategory
                                };
                                new_rec.category_path = preCategory.category_path + "\\" + new_rec.Id;
                                session.SaveOrUpdate(new_rec);
                            }
                            else
                            {
                                //处理没有子类型的父节点
                                if (preCategory.pre_category != null)
                                {
                                    var pre_preCategory = preCategory.pre_category;

                                    var new_rec = new DB_NH.DB_Model.ZJK.ZJ_category()
                                    {
                                        Id = Common.NewID(),
                                        is_leaf = 1,
                                        category_code = preCategory.category_code,
                                        category_level = preCategory.category_level,
                                        category_name = preCategory.category_name,
                                        pre_category = pre_preCategory
                                    };

                                    pre_preCategory.addChild(new_rec);

                                    //将原来的父级节点作为现在新的子节点
                                    preCategory.category_code = "新类型代码";
                                    preCategory.category_name = "新类型名称";
                                    preCategory.category_level = new_rec.category_level + 1;
                                    preCategory.pre_category = new_rec;

                                    new_rec.addChild(preCategory);

                                    session.SaveOrUpdate(pre_preCategory);
                                    session.SaveOrUpdate(new_rec);
                                    session.SaveOrUpdate(preCategory);
                                }
                                else
                                {
                                    //当前节点是根节点
                                    var new_rec = new DB_NH.DB_Model.ZJK.ZJ_category()
                                    {
                                        Id = Common.NewID(),
                                        is_leaf = 1,
                                        category_code = preCategory.category_code,
                                        category_level = preCategory.category_level,
                                        category_name = preCategory.category_name,
                                        pre_category = null
                                    };

                                    //将原来的父级节点作为现在新的子节点
                                    preCategory.category_code = "新类型代码";
                                    preCategory.category_name = "新类型名称";
                                    preCategory.category_level = new_rec.category_level + 1;
                                    preCategory.pre_category = new_rec;

                                    new_rec.addChild(preCategory);

                                    session.SaveOrUpdate(new_rec);
                                    session.SaveOrUpdate(preCategory);
                                }
                            }

                        }
                        else
                        {
                            _returnValue = "父级类型获取错误。";
                        }

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        _returnValue = "系统执行操作错误，错误代码：" + ex.Message;
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 保存当前分类
        /// </summary>
        /// <param name="thisCategoryId">当前要保存的类型ID</param>
        /// <param name="thisCategoryCode">类型代码</param>
        /// <param name="thisCategoryName">类型名称</param>
        /// <returns></returns>
        public JsonResult saveCategory(string thisCategoryId, string thisCategoryCode, string thisCategoryName)
        {
            string _returnValue = string.Empty;

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _category = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                            .Where(c => c.IsValid == 1 && c.Id == thisCategoryId)
                            .SingleOrDefault();

                        if (_category != null)
                        {
                            _category.category_code = thisCategoryCode;
                            _category.category_name = thisCategoryName;
                            session.SaveOrUpdate(_category);
                        }
                        else
                        {
                            _returnValue = "查询指定类型错误，未发现类型记录。";
                        }
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        _returnValue = "操作错误，错误代码：" + ex.Message;
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除指定ID的类型记录
        /// </summary>
        /// <param name="thisCategoryId"></param>
        /// <returns></returns>
        public JsonResult deleteCategory(string thisCategoryId)
        {
            string _returnValue = string.Empty;

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _category = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                            .Where(c => c.IsValid == 1 && c.Id == thisCategoryId)
                            .SingleOrDefault();

                        if (_category != null)
                        {
                            if (_category.sub_categorys.Count > 0)
                            {
                                //还有子节点，不能删除
                                _returnValue = "不能删除当前类型！请首先删除子类型。";
                            }
                            else
                            {
                                //在父级类型的子类型中删除当前类型
                                if (_category.pre_category != null)
                                {
                                    for (int i = 0; i < _category.pre_category.sub_categorys.Count; i++)
                                    {
                                        if (_category.pre_category.sub_categorys[i].Id == _category.Id)
                                        {
                                            _category.pre_category.sub_categorys.RemoveAt(i);
                                            break;
                                        }
                                    }
                                }
                                _category.pre_category = null;
                                _category.IsValid = 0;
                                session.SaveOrUpdate(_category);
                            }

                        }
                        else
                        {
                            _returnValue = "查询指定类型错误，未发现类型记录。";
                        }

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (transaction.IsActive) transaction.Rollback();
                        _returnValue = "删除指定类型错误，错误代码：" + ex.Message;
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }
    }
}